package stark.app.function.appwidget;
import stark.common.basic.utils.BroadcastReceiverUtil;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.RemoteViews;

import com.blankj.utilcode.util.Utils;
import com.stark.appwidget.lib.AppWidgetViewManager;
import com.stark.appwidget.lib.BaseAppWidgetView;

import stark.app.R;
import stark.common.basic.utils.PendingIntentUtil;

/**
 * Author：daizhongbin on 2023/1/5
 * Email：1027154338@qq.com
 * Desc:
 */
public class TestAppWidgetView extends BaseAppWidgetView {

    private int clickCount = 0;
    private String actionClick;

    public TestAppWidgetView(int appWidgetId) {
        super(appWidgetId);
        actionClick = Utils.getApp().getPackageName() + "." + Integer.toHexString(hashCode()) + ".ACTION_CLICK";
        registerReceiver();
    }

    @Override
    public void update(Context context) {
        registerReceiver();

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.test_app_widget);
        Intent intent = new Intent(actionClick);
        PendingIntent pendingIntent = PendingIntentUtil.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setTextViewText(R.id.tvExample, "点击了" + clickCount + "次");
        remoteViews.setOnClickPendingIntent(R.id.tvExample, pendingIntent);
        AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, remoteViews);
    }

    @Override
    public void destroy() {
        unregisterReceiver();
    }

    private BroadcastReceiver mReceiver;

    private void registerReceiver() {
        if (mReceiver == null) {
            mReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    clickCount++;
                    AppWidgetViewManager.getInstance().updateAppWidgetView2Db(TestAppWidgetView.this);
                    update(context);
                }
            };
            IntentFilter filter = new IntentFilter(actionClick);
            BroadcastReceiverUtil.registerReceiver(Utils.getApp(), mReceiver, filter);
        }
    }

    private void unregisterReceiver() {
        if (mReceiver != null) {
            Utils.getApp().unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }

}
